package user

import (
	partner "gitee.com/binny_w/gin-partner"
	"gitee.com/binny_w/gin_starter/core"
	util2 "gitee.com/binny_w/go-util/v2"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"strconv"
	"time"
)

func act(c *gin.Context) {
	p, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	if p == 0 {
		partner.WriteJsonError(c, 680, "参数错误")
		return
	}
	id1 := uint64(p)
	row, _ := c.Get("user")
	user, _ := row.(*util2.MysqlRow)
	if user == nil {
		partner.WriteJsonError(c, 681, "数据错误")
		return
	}
	id := uint64(user.ToInt64("id"))
	if id == id1 || user.ToInt64("actorId") != 0 {
		partner.WriteJsonError(c, 682, "逻辑错误")
		return
	}
	user1, _ := MdlUser.Table.GetOne(c, id1)
	if user1 == nil || user1.ToInt64("deleted_at") > 0 {
		partner.WriteJsonError(c, 683, "目标用户不可用")
		return
	}
	role := correctRole(id, user.ToStr("role"), true)
	role1 := correctRole(id1, user1.ToStr("role"), true)
	timeNow := time.Now()
	timeIssued := timeNow
	if lastLogin := user1.ToInt64("last_login"); lastLogin > 0 {
		timeIssued = time.Unix(lastLogin, 0)
	} else {
		defer func() {
			_, _ = MdlUser.Table.UpdateById(c, &util2.MysqlRow{"last_login": timeNow.Unix()}, id1)
		}()
	}
	claims := &core.JwtUserClaims{
		ActorId:   id,
		ActorName: user.ToStr("name"),
		ActorRole: role,
		Id:        id1,
		Name:      user1.ToStr("name"),
		Role:      role1,
		IP:        c.ClientIP(),
		UA:        c.Request.UserAgent(),
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(timeNow.Add(time.Hour)),
			IssuedAt:  jwt.NewNumericDate(timeIssued),
		},
	}
	token := ""
	var err error
	if token, err = jwt.NewWithClaims(
		jwt.SigningMethodHS256,
		claims,
	).SignedString([]byte(core.Config.GetString("jwt-key"))); err != nil {
		partner.WriteJsonError(c, 684, err.Error())
		return
	}
	partner.WriteJsonSuccess(c, gin.H{
		"actor_id":   claims.ActorId,
		"actor_name": claims.ActorName,
		"id":         claims.Id,
		"name":       claims.Name,
		"role":       claims.Role,
		"token":      token,
	})
}
